#include <rtthread.h>
#include <rtdevice.h>
#include <board.h>
#include <unistd.h>
#include <fcntl.h>
#include "dev_spi_flash_sfud.h"
typedef void (*app_func)(void);

static void jump_to_app(uint32_t app_addr)
{
    app_func jump_func;
    
    /* 关闭中断 */
    rt_hw_interrupt_disable();
    
    /* 设置堆栈指针 */
    __set_MSP(*(volatile uint32_t*)app_addr);
    
    /* 跳转到应用程序 */
    jump_func = (app_func)(*(volatile uint32_t*)(app_addr + 4));
    jump_func();
}

#define APP_ADDRESS 0x24080000  // 定义应用程序运行地址
static int run_in_sram(int argc, char *argv[])
{
    int fd;
    int size;
    char *buffer = (char *)APP_ADDRESS;
    
    /* 尝试打开并读取bin文件 */
    if(argc != 2) return-1;

    if(rt_strcmp(argv[1], "spi") == 0)
        fd = open("/spi/STM32H7B0VBT6-SRAM.bin", O_RDONLY);
    else if(rt_strcmp(argv[1], "qspi") == 0)
        fd = open("/qspi/STM32H7B0VBT6-SRAM.bin", O_RDONLY);
    else if(rt_strcmp(argv[1], "sdcard") == 0)
        fd = open("/sdcard/STM32H7B0VBT6-SRAM.bin", O_RDONLY);
    else
        return -1;

    if (fd >= 0)
    {
        size = read(fd, buffer, 0x10000);  // 读取文件到SRAM
        close(fd);
        
        if (size > 0)
        {
            rt_kprintf("Loaded %d bytes to 0x%08X, jumping to app...\r\n", size, APP_ADDRESS);
            jump_to_app(APP_ADDRESS);
        }
    }
}

// INIT_APP_EXPORT(run_in_sram);
MSH_CMD_EXPORT(run_in_sram, run in sram);
